package com.edu.controller.order;

import com.edu.dto.ResultDto;
import com.edu.entity.OrderEntity;
import com.edu.service.OrdersService;
import com.edu.service.impl.OrdersServiceImpl;
import com.edu.utils.JwtUtils;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;

/**
 * com.edu.controller.orders
 * 2024/7/11 8:55
 *
 * @author Fancy
 * @version 1.0
 */
@WebServlet("/orders/*")
public class OrdersController extends HttpServlet {
    OrdersService ordersService = new OrdersServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        int userId = Integer.parseInt(req.getPathInfo().substring(1));
        LinkedList<OrderEntity> orders = ordersService.getAllOrderByUserId(userId);

        try {
            if (orders == null) {
                String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "获取所有订单信息失败失败");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.success(orders);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        //从请求头获取token
        String token = req.getHeader("token");
        //返回当前操作用户的基本信息
        Map<String, Object> user = JwtUtils.validateToken(token);

        int orderId = Integer.parseInt(req.getPathInfo().substring(1));
        String newStatus = ServletHelper.getRequestBodyAsJson(req).getString("newStatus");
        System.out.println("orderId: " + orderId + ", newStatus: " + newStatus);

        try {
            int resultRow = ordersService.updateOrderStatus(orderId, newStatus, user.get("role").toString());

            if (resultRow >= 1) {
                String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Order information updated successfully.");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "更新失败。权限不足或订单不存在。");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        int orderId = Integer.parseInt(req.getPathInfo().substring(1));
        System.out.println("orderId: " + orderId);

        try {
            int resultRow = ordersService.deleteOrder(orderId);

            if (resultRow >= 1) {
                String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Order information deleted successfully.");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "更新失败。权限不足或订单不存在。");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}
